import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index.js'
import { getUserInfo } from 'utils/cache.js'
Vue.use(Router)

const Home = () => import('pages/home/index.vue') // 首页路由
const CourseIndex = () => import('pages/course/index.vue') // 免费课程路由
const CourseDetail = () => import('pages/course-detail/index.vue') // 免费课程详情路由
const LessonIndex = () => import('pages/lesson/index.vue') // 实战课程路由
const LessonDetail = () => import('pages/lesson-detail/index.vue') // 实战课程详情路由
const ReadIndex = () => import('pages/read/read.vue') // 专栏路由
const ReadDetaiil = () => import('pages/read-detail/read-detail.vue') // 专栏详情路由
const UserCenter = () => import('pages/user/index.vue') // 个人中心路由
const VipCenter = () => import('pages/vip/index.vue') 

const UserCRUD = () => import('pages/admin/user/index')
const CourseCRUD = () => import('pages/admin/course/index')
const ArticleCRUD = () => import('pages/admin/article/index')
const CommentCRUD = () => import('pages/admin/comments/index')

const routes = [
  {
    path: '/crud/user',
    name: 'UserCRUD',
    component:UserCRUD,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/crud/course',
    name: 'CourseCRUD',
    component:CourseCRUD,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/crud/article',
    name: 'ArticleCRUD',
    component:ArticleCRUD,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/crud/comments',
    name: 'CommentCRUD',
    component:CommentCRUD,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/',
    name: 'Index',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component:Home
  },
  {
    path: '/user',
    name: 'UserCenter',
    component:UserCenter,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/vip',
    name: 'VipCenter',
    component:VipCenter,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/course',
    name: 'CourseIndex',
    component: CourseIndex,
  },
  {
    path: '/course/:id',
    name: 'CourseDetail',
    component: CourseDetail,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/lesson',
    name: 'LessonIndex',
    component:LessonIndex
  },
  {
    path: '/lesson/:id',
    name: 'LessonDetail',
    component: LessonDetail,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/read',
    name: 'ReadIndex',
    component:ReadIndex,
  },
  {
    path: '/read/:id',
    name: 'ReadDetaiil',
    component:ReadDetaiil,
    meta: {
      requireAuth: true
    }
  }
]
const router = new Router({
  routes: routes,
  scrollBehavior () {
    return {
      x: 0,
      y: 0
    }
  }
})

// 路由拦截
//路由守卫具体作用：前端每次跳转路由，就判断 localStroage 中有无 token ，没有就跳转到登录页面，有则跳转到对应路由页面
router.beforeEach((to, from, next) => {
  let userinfo = getUserInfo()
  if (to.meta.requireAuth) {
    if (userinfo.username) {
      next()
    } else{
      store.commit('login/SET_SHOW_LOGIN', true)
    }
  } else {
    next()
  }
})


export default router
